package com.example.demo.service.impl;


import com.example.demo.mapper.UsersMapper;
import com.example.demo.pojo.Users;
import com.example.demo.service.UsersService;
import com.example.demo.vo.MyException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UsersServiceImpl  implements UsersService {
    @Autowired
    private UsersMapper usersMapper;

    @Override
    public int addUser(MultipartFile file) throws IOException {
        int result=0;

        List<Users> userList = new ArrayList<>();

        String fileName=file.getOriginalFilename();
        //判断文件类型
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //获取流
        InputStream fileInputStream = file.getInputStream();

        Workbook workbook=null;

        if (suffix.equals("xlsx")){
            workbook=new XSSFWorkbook(fileInputStream);
        }
        else {
           throw  new MyException("文件类型有误");
        }
        //获取第一sheet
        Sheet sheet = workbook.getSheetAt(0);

        if (null!=sheet){
            for (int i = 1; i <=sheet.getLastRowNum() ; i++) {
                Users users = new Users();
                Row row = sheet.getRow(i);
                if (null==row){
                    continue;
                }
                //设置数据类型
                row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                String name = row.getCell(1).getStringCellValue();


                row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                String password = row.getCell(2).getStringCellValue();


                row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
                String email = row.getCell(3).getStringCellValue();


                row.getCell(4).setCellType(Cell.CELL_TYPE_FORMULA);
                Date birthday = row.getCell(4).getDateCellValue();

                users.setName(name);
                users.setPassword(password);
                users.setEmail(email);
                users.setBirthday(birthday);
                userList.add(users);

            }

            for (Users users : userList) {
                /**
                 * 查询是否存在，不存在则添加，存在则修改
                 */
                String name = users.getName();
                int i = usersMapper.selectUsersByName(name);
                if (0==i){
                    usersMapper.addUser(users);
                }else {
                    usersMapper.updateUser(users);
                }
            }
        }
        return 1;
    }
}
